<script setup>
import { computed, reactive, ref,onMounted } from 'vue';
import { getCityStore } from "@/stores/modules/getCity.js";
import {userUserStore} from "@/stores/index.js";
import {message,Modal} from 'ant-design-vue'
import {cloneDeep} from 'lodash'
import {
  addDesiredJob,
  updateDesiredJob,
  deleteDesiredJob,
  getStuInfo,
} from '@/api/stu.js'
import {setStuInfo} from "@/views/resumeCreation/components/contentEdit/share.js";

// 获取城市列表
const jobStatusList = getCityStore().cityList;
const currentIndex = ref(null);
const formRef = ref();

//选项列表 -- 职位
const jobPositionList = [
  { label:'安全评价师', value: '1'},
  { label:'机械工程师', value: '2'},
  { label:'机械工程师', value: '3'},
  { label:'机械工程师', value: '4'},
  { label:'机械工程师', value: '5'},
  { label:'机械工程师', value: '6'},
  { label:'机械工程师', value: '7'},
];

//选项列表 -- 工作类型
const jobTypeList = [
  { label: '全职', value: '全职' },
  { label: '零工/兼职', value: '零工/兼职' },
];

//选项列表 -- 个人偏好
const jobPreferenceList = [
  { label: '技术', value: '1' },
  { label: '管理', value: '2' },
];

// const filter = (inputValue, path) => {
//   return path.some(option => option.label.toLowerCase().indexOf(inputValue.toLowerCase()) > -1);
// };

// 表单数据数组
const formData = reactive([]);
const isAdd = ref(false)

//初始化数据
onMounted(() =>{
  updateFormData()
})

const updateFormData = () =>{
  formData.splice(0)
  Object.assign(formData, userUserStore().userInfo.desiredJobs||[])
}

// 获取选中的城市名称
// const getWorkCityName = (index,item) => {
//   if (formData[index].workCity.length === 0) return "未选择城市";
//
//   const province = jobStatusList.find(prov => prov.code === item[0]);
//   if (!province) return;
//   if (item.length > 1) {
//     const city = province.pchilds?.find(c => c.code === item[1]);
//     if (city) return city.name
//     else return province.name
//   } else {
//     return province.name
//   }
// };

const getWorkCityName = (index,item) => {
  if (formData[index].workCity.length === 0) return "未选择城市";
  return jobStatusList.find(city => city.code === item).name
}

// 添加新职位表单
const onAdd = async () => {
  formData.push(
      {
        jobPosition: null,
        jobType: null,
        salaryRange: [],
        jobPreference: null,
        workCity: [],
      })
  currentIndex.value = formData.length - 1;
  isAdd.value=true
}

// 删除职位表单
const onDelete = async (index) => {
  Modal.confirm({
    title: '确定删除该职位吗？',
    content: '删除后将无法恢复',
    okText: '确定',
    cancelText: '取消',
    async onOk() {  // 将异步处理单独放在外部
      try {
        const resDel = await deleteDesiredJob({
          desiredJobId: formData[index].desiredJobId
        });  // 直接等待删除操作
        if (resDel.data.code === 200) {
          currentIndex.value = null;
          message.success("删除成功");
          const resGet = await setStuInfo();  // 等待更新学生信息
          if ( resGet === 200) {
            updateFormData()
          }
        } else {
          message.error(resDel.data.message);
        }
      } catch (err) {
        message.error(err.message || "删除失败");
      }
    },
  });
};

//编辑
const onEdit = (index) => {
  currentIndex.value = index
};

// 取消编辑，恢复到原始状态
const cancel = async () => {
  const resGet = await setStuInfo();  // 等待更新学生信息
  if ( resGet === 200) {
    updateFormData()
  }
  currentIndex.value=null
};

// 确认提交
const submit = async () => {
  await formRef.value.validate().then(async () => {
    try {
      const resUpdate = (isAdd.value)?(await addDesiredJob(formData[currentIndex.value]))
          : (await updateDesiredJob(formData[currentIndex.value]))
      currentIndex.value = null;
      if(isAdd.value) isAdd.value = false
      if (resUpdate.data.code === 200) {
        message.success("提交成功");

        // 更新学生信息
        const resGet = await setStuInfo();  // 等待更新学生信息
        if ( resGet === 200) {
          updateFormData()
        }
      } else {
        message.error(resUpdate.data.message);
      }
    } catch (err) {
      message.error(err.message || "提交失败");
    }
  }).catch(err => {
    // 处理验证失败情况
    message.error("请检查表单内容是否填写完整");
  });
};

const JobPositionName = (index) => {
  return jobPositionList.find(item => item.value === formData[index].jobPosition)?.label;
}

const JobPreferenceName = (index) => {
  return jobPreferenceList.find(item => item.value === formData[index].jobPreference)?.label;
}

// 样式
const selectStyle = {
  width: "100%",
  height: "45px"
};

const rules = {
  jobPosition: [{ required: true, message: "请选择期望职位" }],
  jobType: [{ required: true, message: "请选择求职类型" }],
  salaryRange: [{ required: true, message: "请选择薪资范围" }],
  workCity: [{ required: true, message: "请选择工作城市" }],
};

const filterOption = (inputValue, option) => {
  // 如果 option.label 存在，则进行匹配，否则直接使用 option.name
  const labelToMatch = option.label ? option.label.toLowerCase() : option.name.toLowerCase();

  return labelToMatch.includes(inputValue.toLowerCase());
};



</script>

<template>
  <!-- 编辑模式 -->
  <div class="edit-container" v-if="currentIndex !== null">
    <h4 style="height: 40px; margin-top: 0;">选择期望职位</h4>
    <a-form layout="vertical" :rules="rules" ref="formRef" :model="formData[currentIndex]">
      <a-row :gutter="80">
        <a-col :span="12">
          <!-- 期望职位 -->
          <a-form-item label="期望职位" name="jobPosition">
            <a-select
                v-model:value="formData[currentIndex].jobPosition"
                placeholder="请选择期望职位"
                :style="selectStyle"
                :options="jobPositionList"
                size="large"
                show-search
                :filter-option="filterOption"
            />
          </a-form-item>
          <!-- 求职类型 -->
          <a-form-item label="求职类型" name="jobType">
            <a-select
                v-model:value="formData[currentIndex].jobType"
                :options="jobTypeList"
                placeholder="请选择求职类型"
                :style="selectStyle"
                size="large"
                :filterOption="filterOption"
            />
          </a-form-item>

          <a-form-item label="工作城市" name="workCity">
            <!-- 级联选择组件 -->
<!--            <a-cascader-->
<!--                suffix-icon="Shopping Around"-->
<!--                max-tag-count="8"-->
<!--                multiple-->
<!--                v-model:value="formData[currentIndex].workCity"-->
<!--                :field-names="{ label: 'name', value: 'code', children: 'pchilds' }"-->
<!--                :show-search="{ filter }"-->
<!--                :options="jobStatusList"-->
<!--                placeholder="请选择工作城市"-->
<!--                size="large"-->
<!--            >-->
            <a-select
                max-tag-count="8"
                mode="multiple"
                :field-names="{ label: 'name', value: 'code' }"
                v-model:value="formData[currentIndex].workCity"
                show-search
                :filterOption="filterOption"
                :options="jobStatusList"
                placeholder="请选择工作城市"
                size="large"
            >
            </a-select>
          </a-form-item>
        </a-col>

        <a-col :span="12">
          <!-- 薪资要求 -->
          <a-form-item label="薪资要求 (元)" name="salaryRange">
            <div style="display: flex; gap: 10px;margin-bottom: 5px">
              <a-input-number
                  v-model:value="formData[currentIndex].salaryRange[0]"
                  placeholder="最低薪资"
                  style="width: 100%;"
                  :min="1000"
                  step="1000"
              />
              <span>-</span>
              <a-input-number
                  v-model:value="formData[currentIndex].salaryRange[1]"
                  placeholder="最高薪资"
                  style="width: 100%;height: 40px"
                  :min="formData[currentIndex].salaryRange[0]+1000"
                  step="1000"
              />
            </div>
          </a-form-item>

          <!-- 职位偏好 -->
          <a-form-item label="职位偏好" name="jobPreference">
            <a-select
                v-model:value="formData[currentIndex].jobPreference"
                :options="jobPreferenceList"
                placeholder="请选择职位偏好"
                :style="selectStyle"
                size="large"
                :filterOption="filterOption"
            />
          </a-form-item>

          <a-form-item>
            <!-- 按钮 -->
            <div class="button-item">
              <a-button size="large" @click="cancel">取消</a-button>
              <a-button type="primary" size="large" @click="submit">确认</a-button>
            </div>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </div>

  <!-- 默认模式 -->
  <div class="default-container" v-else>
    <div style="display: flex; align-items: center;justify-content: space-between">
      <div style="display: flex; align-items: center;">
        <div class="title"></div>
        <h2>期望职位</h2>
      </div>
      <div class="add-info" @click="onAdd">添加</div>
    </div>
    <h4 v-show="formData.length===0">
      尚未选择期望职位
    </h4>
    <div class="user-info" v-for="(item, index) in formData" :key="index" v-if="formData.length!==0">
      <div class="user-info-delicate">
        <span v-if="item.jobPreference">{{ JobPreferenceName(index) }}</span>
        <span v-if="item.jobPosition">{{ JobPositionName(index) }}</span>
        <span v-if="item.jobPosition&&item.salaryRange[0]" style="gap:10px;color: #b8b8bb">|</span>
        <span v-if="item.salaryRange[0]">{{ item.salaryRange[0] }} - {{ item.salaryRange[1] }} 元</span>
      </div>
      <div class="user-info-jobtype">
        <span v-if=" item.jobType"><a-tag>{{ item.jobType }}</a-tag></span>
      </div>
      <div class="user-info-city">
        <span v-for="(item, id) in item.workCity" :key="index">{{getWorkCityName(index,item)}}</span>
      </div>
      <a-space direction="vertical" class="change-container">
        <a-button type="link" @click="onEdit(index)" class="edit-info">编辑</a-button>
        <a-button type="link" @click="onDelete(index)" class="delete-info">删除</a-button>
      </a-space>
    </div>
  </div>
</template>

<style scoped>
.edit-container {
  width: 100%;
  height: 100%;
  background-color: #f5f6fa;
  padding: 20px;
  border-radius: 10px;
}

.default-container {
  width: 100%;
  padding: 20px;
}

.title {
  width: 4px;
  height: 25px;
  background: #00bebd;
  border-radius: 3px;
  margin-right: 10px;
}

.button-item {
  display: flex;
  margin-top: 120px;
  margin-left: 100px;
  justify-content: space-around;
}

a-input-number {
  flex: 1;
}

.user-info {
  min-height: 70px;
  margin-left: 3px;
  margin-top: 10px;
  display: grid;
  cursor: pointer;
  padding: 10px;
  position: relative;
}

.user-info:hover {
  background-color: #e6f7ff;
}

.user-info-city{
  display: flex;
  gap: 10px;
}

.change-container {
  justify-self: end;
  position: absolute;
}

.user-info-delicate,.user-info-jobtype {
  display: flex;
  gap: 20px;
  align-items: center;
}

.user-info-jobtype {
  margin: 10px 0;
}

.user-info-city{
  display: flex;
  gap: 20px;
  >span{
    font-size: 14px;
    color: #595959;
  }
}

.title {
  width: 4px;
  height: 25px;
  background: #00bebd;
  border-radius: 3px;
  margin-top: -8px;
  margin-right: 10px;
}

.add-info {
  display: flex;
  font-size: 14px;
  color: #595959;
  cursor: pointer;
}
</style>

